//
//  LZCartViewController.m
//  LZCartViewController
//
//  Created by LQQ on 16/5/18.
//  Copyright © 2016年 LQQ. All rights reserved.
//  https://github.com/LQQZYY/CartDemo
//  http://blog.csdn.net/lqq200912408
//  QQ交流: 302934443

#import "LZCartViewController.h"
#import "LZConfigFile.h"
#import "LZCartTableViewCell.h"
#import "OO_OrderModel.h"
#import "OO_OrderViewController.h"
@interface LZCartViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    BOOL _isHiddenNavigationBarWhenDisappear;//记录当页面消失时是否需要隐藏系统导航
    BOOL _isHasTabBarController;//是否含有tabbar
    BOOL _isHasNavitationController;//是否含有导航
}

@property (strong,nonatomic)NSMutableArray *dataArray;
@property (strong,nonatomic)NSMutableArray *selectedArray;
@property (strong,nonatomic)UITableView *myTableView;
@property (strong,nonatomic)UIButton *allSellectedButton;
@property (strong,nonatomic)UILabel *totlePriceLabel;
@property (assign,nonatomic)CGFloat navHeight;
@end

@implementation LZCartViewController

#pragma mark - viewController life cicle
- (void)viewWillAppear:(BOOL)animated {

    [self loadData];
    
    //当进入购物车的时候判断是否有已选择的商品,有就清空
    //主要是提交订单后再返回到购物车,如果不清空,还会显示
    if (self.selectedArray.count > 0) {
        for (LZCartModel *model in self.selectedArray) {
            model.selected = NO;//这个其实有点多余,提交订单后的数据源不会包含这些,保险起见,加上了
        }
        [self.selectedArray removeAllObjects];
    }
    
    _allSellectedButton.selected = NO;
    _totlePriceLabel.attributedText = [self LZSetString:@"￥0.00"];

}


-(void)creatData {
    [self.dataArray removeAllObjects];
    JQFMDB *dataBase = [JQFMDB shareDatabase];
    NSArray *arr = [dataBase jq_lookupTable:SHOPCARTABLE dicOrModel:[OO_OrderModel class] whereFormat:@"where logionUser = %@",[UserDefaults readFromPlist:LOGIN_STATUS_TEL]];
    for (OO_OrderModel *model in arr) {
        [self.dataArray addObject:model];
    }
    if (self.myTableView) {
        [self.myTableView reloadData];
    }
    
}
- (void)loadData {
    [self creatData];
    [self changeView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //获取状态栏的rect
    CGRect statusRect = [[UIApplication sharedApplication] statusBarFrame];
    //获取导航栏的rect
    CGRect navRect = self.navigationController.navigationBar.frame;

    self.navHeight  = statusRect.size.height+navRect.size.height;
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _isHasTabBarController = self.tabBarController?YES:NO;
    _isHasNavitationController = self.navigationController?YES:NO;
    
    [self loadData];
    
    
    [self setupCustomNavigationBar];
    if (self.dataArray.count > 0) {
        
        [self setupCartView];
    } else {
        [self setupCartEmptyView];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    if (_isHiddenNavigationBarWhenDisappear == YES) {
        self.navigationController.navigationBarHidden = NO;
    }
    
    NSLog(@"%lf", self.navHeight);
    NSLog(@"%lf",LZTabBarHeight);
}

/**
 *  @author LQQ, 16-02-18 11:02:16
 *
 *  计算已选中商品金额
 */
-(void)countPrice {
    double totlePrice = 0.0;
    
    for (LZCartModel *model in self.selectedArray) {
        
        double price = [model.price doubleValue];
        
        totlePrice += price*model.goodsNumber;
    }
    NSString *string = [NSString stringWithFormat:@"￥%.2f",totlePrice];
    self.totlePriceLabel.attributedText = [self LZSetString:string];
}

#pragma mark - 初始化数组
- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _dataArray;
}

- (NSMutableArray *)selectedArray {
    if (_selectedArray == nil) {
        _selectedArray = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _selectedArray;
}

#pragma mark - 布局页面视图
#pragma mark -- 自定义导航
- (void)setupCustomNavigationBar {
//    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, LZSCREEN_WIDTH, LZNaigationBarHeight)];
//    backgroundView.backgroundColor = LZColorFromRGB(236, 236, 236);
//    [self.view addSubview:backgroundView];
//
//    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, LZNaigationBarHeight - 0.5, LZSCREEN_WIDTH, 0.5)];
//    lineView.backgroundColor = [UIColor lightGrayColor];
//    [self.view addSubview:lineView];
//
//    UILabel *titleLabel = [[UILabel alloc]init];
//    titleLabel.text = @"购物车";
//    titleLabel.font = [UIFont systemFontOfSize:20];
//
//    titleLabel.center = CGPointMake(self.view.center.x, (LZNaigationBarHeight - 20)/2.0 + 20);
//    CGSize size = [titleLabel sizeThatFits:CGSizeMake(300, 44)];
//    titleLabel.bounds = CGRectMake(0, 0, size.width + 20, size.height);
//
//    titleLabel.textAlignment = NSTextAlignmentCenter;
//    [self.view addSubview:titleLabel];
    
//    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    backButton.frame = CGRectMake(10, 20, 40, 44);
//    [backButton setImage:[UIImage imageNamed:lz_BackButtonString] forState:UIControlStateNormal];
//    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:backButton];
}
#pragma mark -- 自定义底部视图 
- (void)setupCustomBottomView {
    
    UIView *backgroundView = [self.view viewWithTag:TAG_CartEmptyView + 1];
    if (!backgroundView) {
        UIView *backgroundView = [[UIView alloc]init];
        backgroundView.backgroundColor = LZColorFromRGB(245, 245, 245);
        backgroundView.tag = TAG_CartEmptyView + 1;
        [self.view addSubview:backgroundView];
        
        //当有tabBarController时,在tabBar的上面
        if (_isHasTabBarController == YES) {
            backgroundView.frame = CGRectMake(0, LZSCREEN_HEIGHT -  2*LZTabBarHeight -  self.navHeight, LZSCREEN_WIDTH, LZTabBarHeight);
        } else {
            backgroundView.frame = CGRectMake(0, LZSCREEN_HEIGHT -  LZTabBarHeight -  self.navHeight, LZSCREEN_WIDTH, LZTabBarHeight);
        }
        
        UIView *lineView = [[UIView alloc]init];
        lineView.frame = CGRectMake(0, 0, LZSCREEN_WIDTH, 1);
        lineView.backgroundColor = [UIColor lightGrayColor];
        [backgroundView addSubview:lineView];
        
        //全选按钮
        UIButton *selectAll = [UIButton buttonWithType:UIButtonTypeCustom];
        selectAll.titleLabel.font = [UIFont systemFontOfSize:16];
        selectAll.frame = CGRectMake(10, 5, 80, LZTabBarHeight - 10);
        [selectAll setTitle:@" 全选" forState:UIControlStateNormal];
        [selectAll setImage:[UIImage imageNamed:lz_Bottom_UnSelectButtonString] forState:UIControlStateNormal];
        [selectAll setImage:[UIImage imageNamed:lz_Bottom_SelectButtonString] forState:UIControlStateSelected];
        [selectAll setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [selectAll addTarget:self action:@selector(selectAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [backgroundView addSubview:selectAll];
        self.allSellectedButton = selectAll;
        
        //结算按钮
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = BASECOLOR_RED;
        btn.frame = CGRectMake(LZSCREEN_WIDTH - 80, 0, 80, LZTabBarHeight);
        [btn setTitle:@"去结算" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(goToPayButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [backgroundView addSubview:btn];
        
        //合计
        UILabel *label = [[UILabel alloc]init];
        label.font = [UIFont systemFontOfSize:18];
        label.textColor = [UIColor redColor];
        [backgroundView addSubview:label];
        
        label.attributedText = [self LZSetString:@"¥0.00"];
        CGFloat maxWidth = LZSCREEN_WIDTH - selectAll.bounds.size.width - btn.bounds.size.width - 30;
        //    CGSize size = [label sizeThatFits:CGSizeMake(maxWidth, LZTabBarHeight)];
        label.frame = CGRectMake(selectAll.bounds.size.width + 20, 0, maxWidth - 10, LZTabBarHeight);
        self.totlePriceLabel = label;
    }else {
        [self.view bringSubviewToFront:backgroundView];
    }
    
    
}

- (NSMutableAttributedString*)LZSetString:(NSString*)string {
    
    NSString *text = [NSString stringWithFormat:@"合计:%@",string];
    NSMutableAttributedString *LZString = [[NSMutableAttributedString alloc]initWithString:text];
    NSRange rang = [text rangeOfString:@"合计:"];
    [LZString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:rang];
    [LZString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:rang];
    return LZString;
}
#pragma mark -- 购物车为空时的默认视图
- (void)changeView {
    if (self.dataArray.count > 0) {
        UIView *view = [self.view viewWithTag:TAG_CartEmptyView];
        if (view != nil) {
            [view removeFromSuperview];
        }
        
        [self setupCartView];
    } else {
        UIView *bottomView = [self.view viewWithTag:TAG_CartEmptyView + 1];
        [bottomView removeFromSuperview];
        
        [self.myTableView removeFromSuperview];
        self.myTableView = nil;
        [self setupCartEmptyView];
    }
}

- (void)setupCartEmptyView {
    
    UIView *backgroundView;
    if (![self.view viewWithTag:TAG_CartEmptyView]) {
        backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0,  self.navHeight, LZSCREEN_WIDTH, LZSCREEN_HEIGHT -  self.navHeight)];
        backgroundView.tag = TAG_CartEmptyView;
        [self.view addSubview:backgroundView];
        
        //默认图片
        UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:lz_CartEmptyString]];
        img.center = CGPointMake(LZSCREEN_WIDTH/2.0, LZSCREEN_HEIGHT/2.0 - 120);
        img.bounds = CGRectMake(0, 0, 247.0/187 * 100, 100);
        [backgroundView addSubview:img];
        
        UILabel *warnLabel = [[UILabel alloc]init];
        warnLabel.center = CGPointMake(LZSCREEN_WIDTH/2.0, LZSCREEN_HEIGHT/2.0 - 10);
        warnLabel.bounds = CGRectMake(0, 0, LZSCREEN_WIDTH, 30);
        warnLabel.textAlignment = NSTextAlignmentCenter;
        warnLabel.text = [CommonAPI userLoginStatus] == YES ? @"购物车为空!" : PLEASELOGINSTR ;
        warnLabel.font = [UIFont systemFontOfSize:15];
        warnLabel.textColor = LZColorFromHex(0x706F6F);
        [backgroundView addSubview:warnLabel];
    }else {
        [self.view bringSubviewToFront:backgroundView];
    }
    
    
}
#pragma mark -- 购物车有商品时的视图
- (void)setupCartView {
    //创建底部视图
    [self setupCustomBottomView];
    UITableView *table;
    if (!_myTableView) {
        table = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        
        table.delegate = self;
        table.dataSource = self;
        
        table.rowHeight = lz_CartRowHeight;
        table.separatorStyle = UITableViewCellSeparatorStyleNone;
        table.backgroundColor = LZColorFromRGB(245, 246, 248);
        [self.view addSubview:table];
        self.myTableView = table;
        if (_isHasTabBarController) {
            table.frame = CGRectMake(0, 0, LZSCREEN_WIDTH, LZSCREEN_HEIGHT -  self.navHeight - 2*LZTabBarHeight);
        } else {
            table.frame = CGRectMake(0, 0, LZSCREEN_WIDTH, LZSCREEN_HEIGHT -  self.navHeight - LZTabBarHeight);
        }
    }
    
    
}
#pragma mark --- UITableViewDataSource & UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LZCartTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LZCartReusableCell"];
    if (cell == nil) {
        cell = [[LZCartTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"LZCartReusableCell"];
    }
    
    LZCartModel *model = self.dataArray[indexPath.row];
    __block typeof(cell)wsCell = cell;
    WeakSelf
    [cell numberAddWithBlock:^(NSInteger number) {
        wsCell.lzNumber = number;
        model.goodsNumber = number;
        
        
        [self.dataArray replaceObjectAtIndex:indexPath.row withObject:model];
        if ([self.selectedArray containsObject:model]) {
            [self.selectedArray removeObject:model];
            [self.selectedArray addObject:model];
            [self countPrice];
        }
        [weakSelf changeDBMethod:model condition:[NSString stringWithFormat:@"where ID = %@",model.ID]];
    }];
    
    [cell numberCutWithBlock:^(NSInteger number) {
        
        wsCell.lzNumber = number;
        model.goodsNumber = number;
        
        [self.dataArray replaceObjectAtIndex:indexPath.row withObject:model];
        
        //判断已选择数组里有无该对象,有就删除  重新添加
        if ([self.selectedArray containsObject:model]) {
            [self.selectedArray removeObject:model];
            [self.selectedArray addObject:model];
            [self countPrice];
        }
        [weakSelf changeDBMethod:model condition:[NSString stringWithFormat:@"where ID = %@",model.ID]];
    }];
    
    [cell cellSelectedWithBlock:^(BOOL select) {
        
        model.selected = select;
        if (select) {
            [self.selectedArray addObject:model];
        } else {
            [self.selectedArray removeObject:model];
        }
//        [weakSelf changeDBMethod:model condition:[NSString stringWithFormat:@"where ID = %@",model.ID]];
        
        if (self.selectedArray.count == self.dataArray.count) {
            weakSelf.allSellectedButton.selected = YES;
        } else {
            weakSelf.allSellectedButton.selected = NO;
        }
        
        [self countPrice];
    }];
    
    [cell reloadDataWithModel:model];
    return cell;
}

-(void)changeDBMethod:(LZCartModel *)model condition:(NSString *)condition{
    if (![CommonAPI StringIsNull:model.ID]) {
        // 数据库修改
        JQFMDB *dataBase = [JQFMDB shareDatabase];
        [dataBase jq_updateTable:SHOPCARTABLE dicOrModel:model whereFormat:condition];
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        WeakSelf
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要删除该商品?删除后无法恢复!" preferredStyle:1];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           
            LZCartModel *model = [self.dataArray objectAtIndex:indexPath.row];
            JQFMDB *dataBase = [JQFMDB shareDatabase];
            [dataBase jq_deleteTable:SHOPCARTABLE whereFormat:[NSString stringWithFormat:@"where ID = %@",model.ID]];
            
            [self.dataArray removeObjectAtIndex:indexPath.row];
            //    删除
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            
            //判断删除的商品是否已选择
            if ([self.selectedArray containsObject:model]) {
                //从已选中删除,重新计算价格
                [self.selectedArray removeObject:model];
                [self countPrice];
            }
            
            if (self.selectedArray.count == self.dataArray.count) {
                weakSelf.allSellectedButton.selected = YES;
            } else {
                weakSelf.allSellectedButton.selected = NO;
            }
            
            if (self.dataArray.count == 0) {
                [self changeView];
            }
            
            [self.myTableView reloadData];
            [self countPrice];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alert addAction:okAction];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }

}
- (void)reloadTable {
    [self.myTableView reloadData];
}
#pragma mark -- 页面按钮点击事件
#pragma mark --- 返回按钮点击事件
- (void)backButtonClick:(UIButton*)button {
    if (_isHasNavitationController == NO) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark --- 全选按钮点击事件
- (void)selectAllBtnClick:(UIButton*)button {
    button.selected = !button.selected;
    
    //点击全选时,把之前已选择的全部删除
    for (LZCartModel *model in self.selectedArray) {
        model.selected = NO;
    }
    
    [self.selectedArray removeAllObjects];
    
    if (button.selected) {
        
        for (LZCartModel *model in self.dataArray) {
            model.selected = YES;
            [self.selectedArray addObject:model];
        }
    }
    
    [self.myTableView reloadData];
    [self countPrice];
}
#pragma mark --- 确认选择,提交订单按钮点击事件
- (void)goToPayButtonClick:(UIButton*)button {
    if (self.selectedArray.count > 0) {
        NSLog(@"%@",self.selectedArray);
//        for (LZCartModel *model in self.selectedArray) {
//            NSLog(@"选择的商品>>%@>>>%ld",model,(long)model.goodsNumber);
//        }
        OO_OrderViewController *vc = [OO_OrderViewController new];
        vc.orderArr = self.selectedArray;
        [self.navigationController pushViewController:vc animated:1];
    } else {
        NSLog(@"你还没有选择任何商品");
        [MBProgressHUD showTipMessageInView:@"你还没有选择任何商品"];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
